package com.sk.sourcecircle.activity.home.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.PathUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.community.fragment.ChatFragment;
import com.sk.sourcecircle.activity.find.act.SatisfyTaskDetailsActvitiy;
import com.sk.sourcecircle.activity.find.act.TaskDetailsActivity;
import com.sk.sourcecircle.activity.main.ShareDetailsActivity;
import com.sk.sourcecircle.activity.mine.act.PreviewViewpagerActivity;
import com.sk.sourcecircle.adapter.ChatDetailsAdapter;
import com.sk.sourcecircle.adapter.OnItemMessageClickListener;
import com.sk.sourcecircle.base.BaseActivity;
import com.sk.sourcecircle.callback.MyCallBack;
import com.sk.sourcecircle.callback.OnItemMessageClick;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.MyEMMessage;
import com.sk.sourcecircle.utils.EaseChatRowVoicePlayer;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.view.EaseVoiceRecorderView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by sk on 2017/11/19.
 */

@RuntimePermissions
public class ChatActivity extends BaseActivity implements EMCallBack, View.OnTouchListener, OnItemMessageClick, BaseQuickAdapter.OnItemChildClickListener, OnItemMessageClickListener {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.data_ryc)
    RecyclerView dataRyc;
    @BindView(R.id.camera)
    ImageView camera;
    @BindView(R.id.icon)
    ImageView icon;
    @BindView(R.id.chat_ll)
    FrameLayout chatLl;
    @BindView(R.id.voice)
    ImageView voice;
    @BindView(R.id.remark_voice)
    TextView remarkVoice;
    @BindView(R.id.ed_content)
    EditText edContent;
    @BindView(R.id.send)
    TextView send;
    @BindView(R.id.voice_recorder)
    EaseVoiceRecorderView voiceRecorder;
    @BindView(R.id.send_ll)
    LinearLayout sendLl;
    @BindView(R.id.group_head)
    TextView groupHead;
    @BindView(R.id.send_image)
    FrameLayout sendImage;
    @BindView(R.id.send_video)
    FrameLayout sendVideo;
    private EMConversation conversation;
    private String userName;
    private int chatType = 1;
    private ChatDetailsAdapter adapter;
    private LinearLayoutManager linearLayoutManager;
    private List<MyEMMessage> allDataList = new ArrayList<>();
    protected InputMethodManager inputManager;
    private String toName = "";
    private String toId = "";
    private String toUrl = "";
    private String groupName = "";

    private EaseChatRowVoicePlayer voicePlayer;

    @Override
    protected int getContentView() {
        return R.layout.activity_chat;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

        voicePlayer = EaseChatRowVoicePlayer.getInstance(mContext);

        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);


        chatType = getIntent().getIntExtra("type", 1);

        if (chatType == 2) {
            groupName = getIntent().getStringExtra("groupName");
            groupHead.setVisibility(View.VISIBLE);
        }

        userName = getIntent().getStringExtra("id");

        toName = getIntent().getStringExtra("toName");

        toId = getIntent().getStringExtra("toId");

        toUrl = getIntent().getStringExtra("toUrl");

        tvTitle.setText(toName);


        linearLayoutManager = new LinearLayoutManager(mContext);

        dataRyc.setLayoutManager(linearLayoutManager);

        conversation = EMClient.getInstance().chatManager().getConversation(userName, MyUtils.getConversationType(chatType), true);
        conversation.getAllMessages();
        List<EMMessage> var = conversation.loadMoreMsgFromDB(null, 50);

        if (conversation.getUnreadMsgCount() > 0) {
            conversation.markAllMessagesAsRead();
            if (ChatFragment.handler != null) {
                ChatFragment.handler.sendEmptyMessage(1);
            }
        }

        for (EMMessage emMessage : var) {
            MyEMMessage myEMMessage = new MyEMMessage();
            myEMMessage.setEmMessage(emMessage);
            allDataList.add(myEMMessage);
        }
        Log.v("EMVideoMessageBody", JSON.toJSONString(allDataList));

        adapter = new ChatDetailsAdapter(allDataList, this,this);
        dataRyc.setAdapter(adapter);
        dataRyc.scrollToPosition(adapter.getItemCount() - 1);
        adapter.setOnItemChildClickListener(this);

        remarkVoice.setOnTouchListener(this);

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @OnClick({R.id.back, R.id.camera, R.id.icon, R.id.voice, R.id.send, R.id.send_image, R.id.send_video, R.id.group_head})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.camera:
                if (sendLl.getVisibility() == View.GONE) {
                    sendLl.setVisibility(View.VISIBLE);
                } else {
                    sendLl.setVisibility(View.GONE);
                }
                break;
            case R.id.icon:
                break;
            case R.id.voice:

                if (sendLl.getVisibility() == View.VISIBLE) {
                    sendLl.setVisibility(View.GONE);
                }

                if (chatLl.getVisibility() == View.VISIBLE) {
                    ChatActivityPermissionsDispatcher.startRecordWithPermissionCheck(ChatActivity.this);
                } else {
                    chatLl.setVisibility(View.VISIBLE);
                    remarkVoice.setVisibility(View.GONE);
                }
                break;
            case R.id.send:
                if (sendLl.getVisibility() == View.VISIBLE) {
                    sendLl.setVisibility(View.GONE);
                }
                EMMessage message = EMMessage.createTxtSendMessage(edContent.getText().toString(), userName);
                message.setMessageStatusCallback(ChatActivity.this);
                if (chatType == 2) {
                    message.setChatType(EMMessage.ChatType.GroupChat);
                    message.setAttribute("groupName", groupName);
                    Log.v("message", groupName);
                }
                message.setAttribute("nickname", MyUtils.getName(mContext));
                message.setAttribute("head_url", MyUtils.getHeadUrl(mContext));
                message.setAttribute("user_id", MyUtils.getCode(mContext));
                message.setAttribute("toName", toName);
                message.setAttribute("toId", toId);
                message.setAttribute("toUrl", toUrl);
                EMClient.getInstance().chatManager().sendMessage(message);
                EMClient.getInstance().chatManager().saveMessage(message);
                doRefresh();
                break;
            case R.id.send_image:
                if (sendLl.getVisibility() == View.VISIBLE) {
                    sendLl.setVisibility(View.GONE);
                }

                PictureSelector.create(ChatActivity.this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .maxSelectNum(1)// 最大图片选择数量 int
                        .imageSpanCount(4)// 每行显示个数 int
                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage(true)// 是否可预览图片 true or false
                        .isCamera(true)// 是否显示拍照按钮 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                        .enableCrop(false)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
                        .compressSavePath(Environment.getExternalStorageDirectory().getPath())//压缩图片保存地址
                        .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                        .cropCompressQuality(90)// 裁剪压缩质量 默认90 int
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

                break;
            case R.id.send_video:
                ChatActivityPermissionsDispatcher.sendVideoWithPermissionCheck(ChatActivity.this);
                break;
            case R.id.group_head:
                Intent intent = new Intent(mContext, GroupPepActivity.class);
                intent.putExtra("id", toId);
                intent.putExtra("name", toName);
                startActivity(intent);
                break;
        }
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void sendVideo() {
        if (sendLl.getVisibility() == View.VISIBLE) {
            sendLl.setVisibility(View.GONE);
        }
        Intent videoIntent = new Intent(mContext, RecorderVideoActivity.class);
        startActivityForResult(videoIntent, 10);
    }

    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForVideo(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("源圈需要使用您的相机权限！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }


    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForVideo() {
        SnackUtils.showError(mRootView, "您拒绝了录音权限！");
    }

    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForVideo() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止相机权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    public void doRefresh() {
        allDataList.clear();
        conversation = EMClient.getInstance().chatManager().getConversation(userName, MyUtils.getConversationType(chatType), true);
        List<EMMessage> var = conversation.getAllMessages();
        for (EMMessage emMessage : var) {
            MyEMMessage myEMMessage = new MyEMMessage();
            myEMMessage.setEmMessage(emMessage);
            allDataList.add(myEMMessage);
        }

        adapter = new ChatDetailsAdapter(allDataList, this,this);
        dataRyc.setAdapter(adapter);
        dataRyc.scrollToPosition(adapter.getItemCount() - 1);
    }


    @Override
    public void onSuccess() {
        Log.v("EMMessage", "success");
        hideKeyboard();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (edContent != null) {
                    edContent.setText("");
                }
            }
        });
        if (ChatFragment.handler != null) {
            ChatFragment.handler.sendEmptyMessage(1);
        }
    }

    @NeedsPermission({Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startRecord() {
        chatLl.setVisibility(View.GONE);
        remarkVoice.setVisibility(View.VISIBLE);
    }

    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForRecord(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("源圈需要使用您的录音权限！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }


    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        SnackUtils.showError(mRootView, "您拒绝了录音权限！");
    }

    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止录音权限,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ChatActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public void onError(int code, String error) {
        Log.v("EMMessage", error);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (edContent != null) {
                    edContent.setText("");
                }
                Toast.makeText(mContext, "消息发送失败!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onProgress(int progress, String status) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerEvent(String s) {
        if (s.equals("msg")) {
            doRefresh();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //imagePath为图片本地路径，false为不发送原图（默认超过100k的图片会压缩后发给对方），需要发送原图传true
                    boolean isCompress = selectList.get(0).isCompressed();
                    EMMessage emMessage;
                    if (isCompress) {
                        emMessage = EMMessage.createImageSendMessage(selectList.get(0).getCompressPath(), false, userName);
                    } else {
                        emMessage = EMMessage.createImageSendMessage(selectList.get(0).getCompressPath(), false, userName);

                    }

                    emMessage.setMessageStatusCallback(ChatActivity.this);
                    if (chatType == 2) {
                        emMessage.setChatType(EMMessage.ChatType.GroupChat);
                        emMessage.setAttribute("groupName", groupName);
                    }
                    emMessage.setAttribute("nickname", MyUtils.getName(mContext));
                    emMessage.setAttribute("head_url", MyUtils.getHeadUrl(mContext));
                    emMessage.setAttribute("user_id", MyUtils.getCode(mContext));
                    emMessage.setAttribute("toName", toName);
                    emMessage.setAttribute("toId", toId);
                    emMessage.setAttribute("toUrl", toUrl);
                    EMClient.getInstance().chatManager().sendMessage(emMessage);
                    EMClient.getInstance().chatManager().saveMessage(emMessage);
                    doRefresh();
                    break;
                case 10:
                    Uri uri = data.getParcelableExtra("uri");
                    String[] projects = new String[]{MediaStore.Video.Media.DATA,
                            MediaStore.Video.Media.DURATION};
                    Cursor cursor = getContentResolver().query(
                            uri, projects, null,
                            null, null);
                    int duration = 0;
                    String filePath = null;

                    assert cursor != null;
                    if (cursor.moveToFirst()) {
                        // path：MediaStore.Audio.Media.DATA
                        filePath = cursor.getString(cursor
                                .getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
                        // duration：MediaStore.Audio.Media.DURATION
                        duration = cursor
                                .getInt(cursor
                                        .getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
                        EMLog.d(TAG, "duration:" + duration);
                    }
                    cursor.close();
                    cursor = null;

                    File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(filePath, 3);
                        ThumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.close();
                        sendVideoMessage(filePath, file.getAbsolutePath(), duration);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
            }
        }
    }

    private void sendVideoMessage(String filePath, String absolutePath, int duration) {

        //videoPath为视频本地路径，thumbPath为视频预览图路径，videoLength为视频时间长度
        EMMessage emMessage = EMMessage.createVideoSendMessage(filePath, absolutePath, duration, userName);
        emMessage.setMessageStatusCallback(ChatActivity.this);
        if (chatType == 2) {
            emMessage.setChatType(EMMessage.ChatType.GroupChat);
            emMessage.setAttribute("groupName", groupName);
        }
        emMessage.setAttribute("nickname", MyUtils.getName(mContext));
        emMessage.setAttribute("head_url", MyUtils.getHeadUrl(mContext));
        emMessage.setAttribute("user_id", MyUtils.getCode(mContext));
        emMessage.setAttribute("toName", toName);
        emMessage.setAttribute("toId", toId);
        emMessage.setAttribute("toUrl", toUrl);
        EMClient.getInstance().chatManager().sendMessage(emMessage);
        EMClient.getInstance().chatManager().saveMessage(emMessage);
        doRefresh();

    }

    /**
     * hide keyboard
     */
    public void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {


        return voiceRecorder.onPressToSpeakBtnTouch(v, event, new EaseVoiceRecorderView.EaseVoiceRecorderCallback() {

            @Override
            public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {

                //filePath为语音文件路径，length为录音时间(秒)
                EMMessage emMessage = EMMessage.createVoiceSendMessage(voiceFilePath, voiceTimeLength, userName);

                emMessage.setMessageStatusCallback(ChatActivity.this);
                if (chatType == 2) {
                    emMessage.setChatType(EMMessage.ChatType.GroupChat);
                    emMessage.setAttribute("groupName", groupName);
                }
                emMessage.setAttribute("nickname", MyUtils.getName(mContext));
                emMessage.setAttribute("head_url", MyUtils.getHeadUrl(mContext));
                emMessage.setAttribute("user_id", MyUtils.getCode(mContext));
                emMessage.setAttribute("toName", toName);
                emMessage.setAttribute("toId", toId);
                emMessage.setAttribute("toUrl", toUrl);
                EMClient.getInstance().chatManager().sendMessage(emMessage);
                EMClient.getInstance().chatManager().saveMessage(emMessage);
                doRefresh();
//                sendVoiceMessage(voiceFilePath, voiceTimeLength);
//                Log.v("onVoiceRecordComplete",voiceFilePath+"dd");
//                Toast.makeText(mContext,voiceFilePath+"dd",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void click(int type, int messageType, int pos, View view) {
        switch (type) {
            case 0:
                switch (messageType) {
                    case 1:
                        break;
                    case 2:
                        EMMessage emMessage1 = allDataList.get(pos).getEmMessage();
                        EMImageMessageBody body2 = (EMImageMessageBody) emMessage1.getBody();
                        ArrayList<String> strings = new ArrayList<>();
                        strings.add(body2.getThumbnailUrl());
                        Intent intent = new Intent(mContext, PreviewViewpagerActivity.class);
                        intent.putExtra("list", strings);
                        intent.putExtra("pos", 0);
                        startActivity(intent);
                        break;
                    case 3:
                        EMMessage emMessage = allDataList.get(pos).getEmMessage();
                        EMVoiceMessageBody body3 = (EMVoiceMessageBody) emMessage.getBody();
                        doPlay(allDataList.get(pos).getEmMessage(), (TextView) view, body3.getLength());

                        break;
                    case 4:
                        EMMessage emMessage4 = allDataList.get(pos).getEmMessage();
                        String url = (String) emMessage4.ext().get("targetUrl");
                        if (url.contains("http")) {
                            Intent intent1 = new Intent(mContext, ShareDetailsActivity.class);
                            intent1.putExtra("url", url);
                            startActivity(intent1);
                        } else {
                            if (url.contains("&")) {
                                String[] strings1 = url.split("&");
                                int id = Integer.parseInt(strings1[0]);
                                int actType = Integer.parseInt(strings1[1]);
                                switch (actType) {
                                    case 1:
                                        Intent actIntent = new Intent(mContext, EventDetailsActivity.class);
                                        actIntent.putExtra("id", id);
                                        startActivity(actIntent);
                                        break;
                                    case 2:
                                        Intent taskIntent = new Intent(mContext, TaskDetailsActivity.class);
                                        taskIntent.putExtra("id", id);
                                        startActivity(taskIntent);
                                        break;
                                    case 3:
                                        Intent sysIntent = new Intent(mContext, SatisfyTaskDetailsActvitiy.class);
                                        sysIntent.putExtra("id", id);
                                        startActivity(sysIntent);
                                        break;
                                }
                            } else {
                                SnackUtils.showError(mRootView, "分享内容不合法！");
                            }
                        }
                        break;
                    case 5:
                        EMMessage emMessage5 = allDataList.get(pos).getEmMessage();
                        Intent intent5 = new Intent(mContext, EaseShowVideoActivity.class);
                        intent5.putExtra("msg", emMessage5);
                        if (emMessage5 != null && emMessage5.direct() == EMMessage.Direct.RECEIVE && !emMessage5.isAcked()
                                && emMessage5.getChatType() == EMMessage.ChatType.Chat) {
                            try {
                                EMClient.getInstance().chatManager().ackMessageRead(emMessage5.getFrom(), emMessage5.getMsgId());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        startActivity(intent5);
                        break;
                }

                break;
            case 1:
                switch (messageType) {
                    case 1:
                        break;
                    case 2:

                        EMMessage emMessage1 = allDataList.get(pos).getEmMessage();
                        EMImageMessageBody body2 = (EMImageMessageBody) emMessage1.getBody();

                        if (body2.getLocalUrl() != null && new File(body2.getLocalUrl()).exists()) {
                            Intent intent = new Intent(mContext, SinglePreviewActivity.class);
                            intent.putExtra("url", body2.getLocalUrl());
                            startActivity(intent);
                        } else {
                            ArrayList<String> strings = new ArrayList<>();
                            strings.add(body2.getThumbnailUrl());
                            Intent intent = new Intent(mContext, PreviewViewpagerActivity.class);
                            intent.putExtra("list", strings);
                            intent.putExtra("pos", 0);
                            startActivity(intent);
                        }

                        break;
                    case 3:
                        EMMessage emMessage = allDataList.get(pos).getEmMessage();
                        EMVoiceMessageBody body3 = (EMVoiceMessageBody) emMessage.getBody();
                        doPlay(allDataList.get(pos).getEmMessage(), (TextView) view, body3.getLength());
                        break;
                    case 4:
                        EMMessage emMessage4 = allDataList.get(pos).getEmMessage();
                        String url = (String) emMessage4.ext().get("targetUrl");
                        if (url.contains("http")) {
                            Intent intent1 = new Intent(mContext, ShareDetailsActivity.class);
                            intent1.putExtra("url", url);
                            startActivity(intent1);
                        } else {
                            if (url.contains("&")) {
                                String[] strings = url.split("&");
                                int id = Integer.parseInt(strings[0]);
                                int actType = Integer.parseInt(strings[1]);
                                switch (actType) {
                                    case 1:
                                        Intent actIntent = new Intent(mContext, EventDetailsActivity.class);
                                        actIntent.putExtra("id", id);
                                        startActivity(actIntent);
                                        break;
                                    case 2:
                                        Intent taskIntent = new Intent(mContext, TaskDetailsActivity.class);
                                        taskIntent.putExtra("id", id);
                                        startActivity(taskIntent);
                                        break;
                                    case 3:
                                        Intent sysIntent = new Intent(mContext, SatisfyTaskDetailsActvitiy.class);
                                        sysIntent.putExtra("id", id);
                                        startActivity(sysIntent);
                                        break;
                                }
                            } else {
                                SnackUtils.showError(mRootView, "分享内容不合法！");
                            }
                        }

                        break;
                    case 5:
                        EMMessage emMessage5 = allDataList.get(pos).getEmMessage();
                        Intent intent5 = new Intent(mContext, EaseShowVideoActivity.class);
                        intent5.putExtra("msg", emMessage5);
                        if (emMessage5 != null && emMessage5.direct() == EMMessage.Direct.RECEIVE && !emMessage5.isAcked()
                                && emMessage5.getChatType() == EMMessage.ChatType.Chat) {
                            try {
                                EMClient.getInstance().chatManager().ackMessageRead(emMessage5.getFrom(), emMessage5.getMsgId());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        startActivity(intent5);
                        break;
                }
                break;
        }
    }

    private void doPlay(EMMessage message, TextView view, int length) {


        String msgId = message.getMsgId();

        if (voicePlayer.isPlaying()) {
            // Stop the voice play first, no matter the playing voice item is this or others.
            voicePlayer.stop();
            // Stop the voice play animation.
            view.setText(length + "s");
            // If the playing voice item is this item, only need stop play.
            String playingId = voicePlayer.getCurrentPlayingId();
            if (msgId.equals(playingId)) {
                return;
            }
        }

        if (message.direct() == EMMessage.Direct.SEND) {
            // Play the voice
            String localPath = ((EMVoiceMessageBody) message.getBody()).getLocalUrl();
            File file = new File(localPath);
            if (file.exists() && file.isFile()) {
                playVoice(message, view, length);
                // Start the voice play animation.
                view.setText("播放中...");
//                ((EaseChatRowVoice) getChatRow()).startVoicePlayAnimation();
            } else {
                asyncDownloadVoice(message);
            }
        } else {
            final String st = "下载语音文件，请稍后!";
            if (message.status() == EMMessage.Status.SUCCESS) {
                if (EMClient.getInstance().getOptions().getAutodownloadThumbnail()) {
                    play(message, view, length);
                } else {
                    EMVoiceMessageBody voiceBody = (EMVoiceMessageBody) message.getBody();
                    EMLog.i(TAG, "Voice body download status: " + voiceBody.downloadStatus());
                    switch (voiceBody.downloadStatus()) {
                        case PENDING:// Download not begin
                        case FAILED:// Download failed
//                            getChatRow().updateView(getMessage());
                            asyncDownloadVoice(message);
                            break;
                        case DOWNLOADING:// During downloading
                            Toast.makeText(mContext, st, Toast.LENGTH_SHORT).show();
                            break;
                        case SUCCESSED:// Download success
                            play(message, view, length);
                            break;
                    }
                }
            } else if (message.status() == EMMessage.Status.INPROGRESS) {
                Toast.makeText(mContext, st, Toast.LENGTH_SHORT).show();
            } else if (message.status() == EMMessage.Status.FAIL) {
                Toast.makeText(mContext, st, Toast.LENGTH_SHORT).show();
                asyncDownloadVoice(message);
            }
        }
    }

    @SuppressLint("StaticFieldLeak")
    private void asyncDownloadVoice(final EMMessage message) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                EMClient.getInstance().chatManager().downloadAttachment(message);
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
            }
        }.execute();
    }

    private void play(EMMessage message, TextView view, int l) {
        String localPath = ((EMVoiceMessageBody) message.getBody()).getLocalUrl();
        File file = new File(localPath);
        if (file.exists() && file.isFile()) {
            ackMessage(message);
            playVoice(message, view, l);
            // Start the voice play animation.
            view.setText("播放中...");
//            ((EaseChatRowVoice) getChatRow()).startVoicePlayAnimation();
        } else {
            EMLog.e(TAG, "file not exist");
        }
    }

    private void ackMessage(EMMessage message) {
        EMMessage.ChatType chatType = message.getChatType();
        if (!message.isAcked() && chatType == EMMessage.ChatType.Chat) {
            try {
                EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
        }
        if (!message.isListened()) {
            EMClient.getInstance().chatManager().setVoiceMessageListened(message);
        }
    }

    private void playVoice(EMMessage msg, final TextView view, final int l) {
        voicePlayer.play(msg, new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // Stop the voice play animation.
                view.setText(l + "s");
//                ((EaseChatRowVoice) getChatRow()).stopVoicePlayAnimation();
            }
        });
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.head_img:
                Intent intent = new Intent(mContext, PersonDetailsActivity.class);
                EMMessage emMessage = allDataList.get(position).getEmMessage();
                String userId = emMessage.ext().get("user_id") + "";
                if (userId.length() > 0) {
                    intent.putExtra("id", Integer.parseInt(userId));
                    startActivity(intent);
                }
                break;

        }
    }

    @Override
    public void longClickItem(final int pos) {
        TipDialogFragment tipDialogFragment = new TipDialogFragment();
        tipDialogFragment.setContent("是否删除该条聊天记录？");
        tipDialogFragment.setMyCallBack(new MyCallBack() {
            @Override
            public void releaseAlbum() {

            }

            @Override
            public void joinGroup() {

            }

            @Override
            public void takePhoto() {

            }

            @Override
            public void choosePhoto() {

            }

            @Override
            public void sure() {
                EMConversation conversation = EMClient.getInstance().chatManager().getConversation(userName);
                conversation.removeMessage(allDataList.get(pos).getEmMessage().getMsgId());
                allDataList.remove(pos);
                adapter.notifyItemRemoved(pos);
            }

            @Override
            public void cancelOder(String string) {

            }

            @Override
            public void chooseGroup(String id) {

            }

            @Override
            public void cancel() {

            }

            @Override
            public void sendText(String comment) {

            }
        });
        tipDialogFragment.show(getSupportFragmentManager(), "delete");
    }
}
